<template>
    <div class="flex flex-center overflow-hidden avatar" :class="{ 'user': props.name,'icon':!props.src && !props.name }"
        :style="{ width: width + 'px', height: width + 'px',backgroundColor: props.name ? getRandomPresetColor() : '' }">
        <img :src="props.src" :alt="props.name" v-if="props.src">
        <p v-else-if="props.name">{{ firstName(props.name) }}</p>
        <svg-icon size="16px" icon-class="user-line" v-else></svg-icon>
    </div>
</template>

<script setup lang="ts">
const props = defineProps<{
    width?: number;
    src?: string;
    name?: string;
}>()

function firstName(name: string) {
    for (const char of name) {
    return char.toUpperCase();
  }
  return '';
}
const presetColors = ['#fb6b74', '#f5ad37', '#6e7bfe', '#f5ad37', '#96d078', '#999999']

function getRandomPresetColor(): string {
    const randomIndex = Math.floor(Math.random() * presetColors.length)
    return presetColors[randomIndex]
}
</script>

<style scoped>
.avatar {
    width: 32px;
    height: 32px;
    overflow: hidden;
    border-radius: 50%;
    background-color: var(--mainBg);

    &>img {
        width: 100%;
        height: 100%;
    }

    &.user {
        background-color: #f9e3cf;

        p {
            font-size: 14px;
            color: #ffffff;
        }
    }

    &.icon {
        background-color: #96d078;

        &>img {
            display: none;
        }

        &>p {
            display: none;
        }

        &>svg {
            color: #ffffff;
            margin:0;
        }
    }

}
</style>